# -*- coding: utf-8 -*-

from mainapp.settings import DM_METHODS

def compare_items(x,y):
    
    if x[0] > y[0]:
        return 1
    elif x[0] < y[0]:
        return -1
    else:
        return 0


def get_dm_methods():
    
    '''Return methods as list of tuples eg. [(method_name, method_value),(,)]'''
    
    return sorted(DM_METHODS.items(), cmp=compare_items)

def get_dm_methods_as_choices():
    
    '''Implemented for form field option "choices"'''
    
    methods = get_dm_methods()
    
    return [(method_index, methods[method_index][0]) for method_index in range(len(methods))]


def get_dm_method_name(method_index):
    
    '''Returns name of method from given index'''
    
    return get_dm_methods()[method_index][0]

def get_dm_modules(method_index=None, method_name=None):
    
    '''Returns modules as list of tuples'''
    
    if method_index is not None or method_name is not None:
        
        methods = get_dm_methods()
        modules = []        
        
        if method_index is not None:
            
            method = methods[method_index][1]
        
        else:
            
            for iter_method in methods:
                
                if iter_method[0] == method_name:                    
                    method = iter_method[1]
                    break
            
        for package in method.items():
            
            package_name = package[0]
            
            for module in package[1].items():
                
                module_name = module[0]
                module_value = module[1]
                
                modules.append(('%s.%s'%(package_name, module_name), module_value))
    
        return sorted(modules, cmp=compare_items)
        
    else:
        
        return Exception('You have to pass parameter')


def get_dm_modules_as_choices(method_index=None, method_name=None):
    
    modules = get_dm_modules(method_index=method_index, method_name=method_name)
    
    return [(module_index, modules[module_index][0]) for module_index in range(len(modules))]
    
    
    

def get_dm_module_by_name(module_name):
    
    '''Returns tuple (name, value)'''
    
    for method in get_dm_methods():
        
        for module in get_dm_modules(method_name=method[0]):
            
            if module_name == module[0]:
                
                return module
        

def get_dm_module_by_indexes(method_index, module_index):
    
    '''Returns tuple (name, value)'''
    
    methods = get_dm_methods()
    
    method = methods[method_index]
    modules = get_dm_modules(method_name=method[0])
    
    return modules[module_index]
    


if __name__ == '__main__':
    
    assert get_dm_modules(method_name=u"Analiza skupień") == get_dm_modules(method_index=0)
    
    print get_dm_module_by_name('rpy2.hierarchical')
    print get_dm_module_by_indexes(0, 0)
    print get_dm_methods_as_choices()
    print get_dm_modules_as_choices(method_index=2)
    

    